package com.eascs.web.o2o.web.controller;

import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.doc.excel.RowReadHandler;
import com.eascs.common.util.StringUtil;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.o2o.web.entity.BankLoanProgressEntity;
import com.eascs.web.o2o.web.exception.InvalidLoaneeException;
import com.eascs.web.o2o.web.form.BankLoanProgressForm;
import com.eascs.web.o2o.web.service.BankLoanProgressService;
import com.eascs.web.o2o.web.util.BankRowWriteHandler;
import com.eascs.web.o2o.web.util.BrowserUtils;
import com.eascs.web.sso.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;

/**
 * 银行申报进度跟进表
 */
@RestController
@RequestMapping("/bankloan/progress")
public class BankLoanProgressFollowRestController extends BaseRestController {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	BankLoanProgressService bankLoanProgressService;

	@RequestMapping("/data")
	public PaginationRestResult data(BankLoanProgressForm form) {
		String o2ourl   = "/bankloan/progress/data";
		String titles[] = {"省区", "平台编码", "借款人", "金额(万元)", "分配时间", "提报时间", "申报状态", "备注", "跟进人"};

		form.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult    = bankLoanProgressService.pageBankLoanProgress(form);
		PaginationInfo       o2oPagingInfo = new PaginationInfo(pageResult, titles, o2ourl);
		o2oPagingInfo.setBuildPagingNavigation(true);
		o2oPagingInfo.setFirstRenderColumnIndex(0);

		ViewContext.put("oaurl", o2ourl);
		ViewContext.put("vo", form);
		ViewContext.put("paginationInfo", o2oPagingInfo);

		return PaginationRestResult.buildPaginationRestResult(o2oPagingInfo);
	}

	@RequestMapping("/toImport")
	public HtmlRestResult toImport() {
		return HtmlRestResult.popHtmlFragment("bankloanProgress/bankLoanProgressImport");
	}

	@RequestMapping("/upload")
	public BaseRestResult<String> upload(@RequestParam(value = "file") MultipartFile file) {
		try {
			ExcelApiHelper.readHandle(file.getInputStream(), new RowReadHandler() {
				@Override
				public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
					if (sheetIndex > 0) {
						return;
					}
					List<Object> result = Arrays.asList(rowDatas);
					if (rowIndex > 0) {
						String province = (String) result.get(0);
						String plateformCode = result.get(1) instanceof String ? ((String) result.get(1)) :
								Integer.valueOf(((Double) result.get(1)).intValue()).toString();
						String loanee = (String) result.get(2);
						if (StringUtil.isBlank(province)) {
							return;
						}


						BankLoanProgressEntity entity = new BankLoanProgressEntity();
						entity.setProvince(province);
						entity.setPlatformCode(plateformCode);
						entity.setLoanee(loanee);
						entity.setLoanAmount(((Double) result.get(3)).intValue() + "");
						entity.setAllocatedTime(((String) result.get(4)).replace("-", "/"));
						entity.setSubmitReportTime(((String) result.get(5)).replace("-", "/"));
						entity.setDeclareStatus((String) result.get(6));
						entity.setRemark((String) result.get(7));
						entity.setFollower((String) result.get(8));
						entity.setOperator(UserHolder.getUser().getCname());
						entity.setOperatorId(UserHolder.getUser().getNo());

						boolean loaneeFlag = bankLoanProgressService.checkLoaneeFromService(province, plateformCode, loanee);
						if (!loaneeFlag) {
							String pattern = "无效的贷款人，省份【{0}】，平台ID【{1}】，借款人【{2}】";
							throw new InvalidLoaneeException(MessageFormat.format(pattern, new Object[]{province, plateformCode, loanee}));
						}
						boolean recordFlag = bankLoanProgressService.findBankLoanProgressByParams(plateformCode, plateformCode,
								loanee, entity.getAllocatedTime());
						//记录存在，更新掉
						if (recordFlag) {
							bankLoanProgressService.update(entity);
						} else {//记录不存在，新增
							bankLoanProgressService.add(entity);
						}
					}
				}
			});
		} catch (Exception e) {
			String message = e.getMessage();
			logger.error(message);
			if (message.indexOf(":") > 0) {
				return BaseRestResult.warn(message.split(":")[1]);
			} else {
				return BaseRestResult.warn(message);
			}
		}

		return BaseRestResult.warn("导入成功");
	}

	@RequestMapping("/download")
	public BaseRestResult<String> download(BankLoanProgressForm form, HttpServletResponse httpServletResponse, HttpServletRequest request)
			throws ParseException, IOException {
		String fileName  = "银行申报进度跟进表";
		String userAgent = request.getHeader("USER-AGENT");
		fileName = BrowserUtils.encodeFileName(userAgent, fileName);

		httpServletResponse.reset();
		httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
		httpServletResponse.setContentType("application/octet-stream; charset=UTF-8");

		List<Object[]>      data            = bankLoanProgressService.listBankLoanProgress(form);
		BankRowWriteHandler bankLoanHandler = new BankRowWriteHandler(data, 9, null, null, 0, 1, 0);
		ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(),
				this.getClass().getResourceAsStream("/excelTemplate/bank_loan_progress_follow.xls"), bankLoanHandler);

		return null;
	}

	@RequestMapping("/templateDownload")
	public BaseRestResult<String> tempalteDownload(HttpServletResponse httpServletResponse, HttpServletRequest request)
			throws ParseException, IOException {
		String fileName  = "银行申报进度跟进表";
		String userAgent = request.getHeader("USER-AGENT");
		fileName = BrowserUtils.encodeFileName(userAgent, fileName);

		httpServletResponse.reset();
		httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
		httpServletResponse.setContentType("application/octet-stream; charset=ISO-8859-1");

		OutputStream out = httpServletResponse.getOutputStream();
		InputStream  in  = this.getClass().getResourceAsStream("/excelTemplate/bank_loan_progress_follow.xls");

		byte[] buffer = new byte[1024];
		int    len;
		while ((len = in.read(buffer)) > 0) {
			out.write(buffer, 0, len);
		}
		return null;
	}
}
